﻿using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;

namespace Tests.Example1
{
    /// <summary>
    /// Helpers to access embedded resources.
    /// </summary>
    public static class AssemblyExtensions
    {
        /// <summary>
        /// Retrieves the embedded resource with the given name as text.
        /// </summary>
        /// <param name="name">The name of the embedded resource.</param>
        /// <param name="assembly">The assembly that contains the embedded resource.</param>
        /// <exception cref="ArgumentNullException">name or assembly are null</exception>
        /// <exception cref="ArgumentException">No resource with the given name could be located.</exception>
        public static string RetrieveTextByName(this Assembly assembly , string name )
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (assembly == null)
                throw new ArgumentNullException("assembly");

            using (Stream stream = assembly.GetManifestResourceStream(name))
            {
                if (stream == null)
                    throw new ArgumentException(
                        String.Format(CultureInfo.InvariantCulture, "No resource with name '{0}' could be located.", name), "name");

                var reader = new StreamReader(stream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }


        public static Stream RetrieveStreamByName(this Assembly assembly, string name)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            if (assembly == null)
                throw new ArgumentNullException("assembly");

            Stream stream = assembly.GetManifestResourceStream(name);
            
                if (stream == null)
                    throw new ArgumentException(
                        String.Format(CultureInfo.InvariantCulture, "No resource with name '{0}' could be located.", name), "name");

            return  stream;
                  

        }
    }



}